<?php
namespace app\admin\service;
use app\common\service\Base;

/**
 * Index 图表处理
 * 作者:bool
 * QQ  :30024167
 */
class Chart extends Base
{
	/**
	 * [__construct 构造方法]
	 */
	function __construct()
	{
		parent::__construct();
	}

	// 统计数据
	public function count_data()
	{
		return [
			'product' => [
				'name'	=>	'产品数量',
				'ico'	=>	'fa-microphone',
				'num'	=>	model('Product')->count()
			],
			'sale' => [
				'name'	=>	'销售单数',
				'ico'	=>	'fa-anchor',
				'num'	=>	model('Sale')->count()
			],
			'purchase' => [
				'name'	=>	'采购单数',
				'ico'	=>	'fa-magnet',
				'num'	=>	model('Purchase')->count()
			],
			'outdepot' => [
				'name'	=>	'出库单数',
				'ico'	=>	'fa-microphone',
				'num'	=>	model('Outdepot')->count()
			]
		];

	}

	// 运营情况
	public function operation(){
		$m = date('Y-m',time());
		$res = [
			'purchase'	=>	$this->get_12_Month($m,model('purchase')),
			'indepot'	=>	$this->get_12_Month($m,model('indepot')),
			'sale'		=>	$this->get_12_Month($m,model('sale')),
			'outdepot'	=>	$this->get_12_Month($m,model('outdepot')),
		];

		return $this->_operation($res);
	}

	// 获取上个月
	public function getlastMonth($date){
		$timestamp=strtotime($date);
		return date('Y-m',strtotime(date('Y',$timestamp).'-'.(date('m',$timestamp)-1).'-01'));
	}


	// 获取最近12个月
	public function get_12_Month($date,$model){
		$temp = [];
		$temp[] = $model->getMonth($date);
		for ($i=1; $i < 12; $i++) { 
			$date = $this->getlastMonth($date);
			$temp[] =  $model->getMonth($date);
		}
		return 	$temp;
	}

	// 运营情况 - 组装成 - 图表所需要的数据
	public function _operation($data){
		$temp = [];
		foreach ($data as $k => $v) {
			// 日期倒序
			$v = array_reverse($v);
			foreach ($v as $kk => $vv) {
				$temp[$k]['money'][] = (int)$vv['count'];
				$temp[$k]['sum'][] = (int)$vv['total'];
				$temp['name'][] = $vv['month'];
			}
		}
		return $temp;
	}

	// 获取省份地图
	public function map(){
		$data = file_get_contents( env('root_path').'extend/map.json' );
		$map = json_decode($data,true);

		$temp = [];
		foreach ($map as $k => $v) {
			$res = model('customer')
			->field('count(id) as count')
			->where('province','like','%'.$v['name'].'%')
			->find();
			$temp[] = [
				'name'	=>	$v['name'],
				'value'	=>	(int)$res['count']
			];
		}
		return $temp;
	}

	// SELECT id,channel,count FROM b_sale GROUP BY channel
	//平台销售占比
	public function channel(){
		$channel = model('Sale')
		->field('channel,sum(count) total')
		->group('channel')
		->select();

		$temp = [];
		foreach ($channel as $k => $v) {
			$temp[] = [
				$v['channel'],
				(int)$v['total']
			];
		}
		$temp[] = [
			'name'	=>	'其他',
			'y'		=> 	0.7,
		];
		return $temp;
	}

}
